package com.powernode.web.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.powernode.constant.Constants;
import com.powernode.dao.domain.PmsOperator;
import com.powernode.dao.mapper.PmsOperatorMapper;
import com.powernode.exceptions.BossException;
import com.powernode.util.JWTUtil;
import com.powernode.util.RedisUtil;
import com.powernode.web.model.dto.LoginTokenDto;
import com.powernode.web.model.query.LoginQuery;
import com.powernode.web.result.RespCode;
import com.powernode.web.service.OperatorService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

@Service
public class OperatorServiceImpl implements OperatorService {

    @Resource
    private PmsOperatorMapper pmsOperatorMapper;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public LoginTokenDto accessToken(LoginQuery loginQuery) {

        // 通过login_name字段查找用户
        PmsOperator pmsOperator = pmsOperatorMapper.selectOne(
                new QueryWrapper<PmsOperator>().eq("login_name", loginQuery.getLoginName()));

        // 判断查找用户是否为空，如果未查找到用户，抛出自定义异常
        if (pmsOperator == null) {
            throw new BossException(RespCode.LOGIN_NAME_ERROR);
        }
        // 获取字段salt盐值,组合前端输入的密码，进行md5加密。得出的加密密码与字段login_pwd对比
        String LoginPwdMd5 = DigestUtil.md5Hex(loginQuery.getLoginPwd() + pmsOperator.getSalt());
        // 判断密码是否正确，如果不正确，抛出自定义异常
        if (!pmsOperator.getLoginPwd().equals(LoginPwdMd5)) {
            throw new BossException(RespCode.LOGIN_NAME_PWD_ERROR);
        }

        // 登录信息正常，生成jwt
        // 利用HuTool创建Json对象，加入键值对:用户id
        JSONObject userJson = new JSONObject();
        userJson.set("id", pmsOperator.getId());
        // 将Json对象转化为String，toJSONString方法参数为缩进空格数
        String token = JWTUtil.createToken(userJson.toJSONString(0), 120);

        // 将token存入Redis
        // token以相关信息，组成Map
        HashMap<String, String> data = new HashMap<>();
        // pmsOperator的id为Long类型
        data.put("id", String.valueOf(pmsOperator.getId()));
        data.put("jwt", token);
        // 登录时间取格式化后的当前时间
        data.put("loginTime", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        boolean saveRedis = redisUtil.setHashValues(Constants.LOGIN_TOKEN + pmsOperator.getId(), data, 120);
        // 如果redis存储信息不正确，抛出异常
        if (!saveRedis) {
            throw new BossException(RespCode.UNKNOWN);
        }

        // 数据返回前端
        return new LoginTokenDto(pmsOperator.getId(), pmsOperator.getShowName(), token);
    }
}
